import { config, createHashHistory } from 'ice';
import { message } from 'antd';
import store from './store';

const router = createHashHistory();

// 根据不同的 url 配置不同的拦截器
const UrlInterceptors = [
  {
    test: /\/stat\//,
    onRequest(request) {
      // application/json 请求体转为 x-www-form-urlencoded
      if (request.method === 'post' && typeof request.data === 'object' && !(request.data instanceof FormData)) {
        request.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
        const formBody = Object.keys(request.data)
          .map((key) => `${key}=${request.data[key] ?? ''}`)
          .join('&');
        request.data = formBody;
      }
    },
    onResponse(response, valid: boolean, msgStr: string) {
      // 大屏不做异常提示，默认返回一个空值
      if (!valid) {
        console.log(`大屏---${response.config.url}---`, msgStr); // log异常
        response.data = undefined;
        return response;
      }

      if ('data' in response.data) return response.data; // 如果有 'data' 属性，返回包裹后的值
      return response;
    },
  },
];

// 构造请求器
const newInterceptors = (silence: boolean, successCode: number | number[] = 0, messageKey = 'message') => {
  successCode = Array.isArray(successCode) ? successCode : [successCode];

  const interceptors = {
    request: {
      onConfig(request) {
        const interceptor = UrlInterceptors.find((item) => item.test.test(request.url));
        if (interceptor && interceptor.onRequest) interceptor.onRequest(request);

        //  request.headers['authorization'] = localStorage.getItem('authorinfo');
        const authHeader = localStorage.getItem('authorinfo');
        if (authHeader) {
          request.headers['authorization'] = authHeader;
        }
        return request;
      },
    },
    response: {
      onConfig(response) {
        // 默认的结果处理流程
        const { code, [messageKey]: msgStr, msg } = response.data;
        // 自定义结果处理
        const interceptor = UrlInterceptors.find((item) => item.test.test(response.config.url));
        if (interceptor && interceptor.onResponse) {
          return interceptor.onResponse(response, successCode.includes(code), msgStr);
        }

        if (successCode.includes(code)) {
          return response;
        } else if (!silence) {
          message.error(`操作失败：${msgStr ? msgStr : msg}`);
        }

        // 处理非 200 的情况
        return Promise.reject(new Error(`HTTP 错误，状态码: ${status}`));
      },
      onError(error) {
        let errorMsg = '';
        // 处理异常情况
        if (error && error.response) {
          switch (error.response.status) {
            case 403:
              errorMsg = '拒绝访问';
              break;
            case 502:
              errorMsg = '服务器端出错';
              break;
            case 401:
              errorMsg = '登录状态已过期，请重新登录';
              store.getModelDispatchers('user').logout();
              router.push('/login');
              break;
            default:
              errorMsg = `连接错误 ${error.response.status}`;
          }
        } else {
          // 处理超时等错误
          errorMsg = '服务器响应超时，请刷新当前页';
        }

        if (!silence) {
          message.error(errorMsg);
        }

        // 返回 Promise.reject，以确保正确处理错误逻辑
        return Promise.reject(error);
      },
    },
  };

  return interceptors;
};

// 请求实例
const request = [
  {
    baseURL: `${config.base_url}`,
    interceptors: newInterceptors(false, [0, 200], 'message'),
  },
  {
    instanceName: 'dataUrl',
    baseURL: `${config.data_url}`,
    interceptors: newInterceptors(false, 0, 'message'),
  },
];

export default request;
